package org.jeecg.modules.online.graphreport.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.BrowserUtils;
import org.jeecg.modules.online.graphreport.entity.OnlGraphreportHead;
import org.jeecg.modules.online.graphreport.service.IOnlGraphreportApiService;
import org.jeecg.modules.online.graphreport.service.IOnlGraphreportHeadService;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @Title: Controller
 * @Description: 图表报告
 * @Author:jeecg-boot
 * @Date: 2019-04-11
 * @Version:V1.0
 */
@RestController("onlGraphreportApiController")
@RequestMapping("/online/graphreport/api")
@Slf4j
public class OnlGraphreportApiController {

	@Autowired
	private IOnlGraphreportHeadService headService;
	@Autowired
	private IOnlGraphreportApiService apiService;

	/**
	 * 获取多数据源模板图表数据
	 */
	@GetMapping(value = "/getTempletAllData")
	public Result<?> getTempletAllData(@RequestParam(name = "id", required = true) String id) {
		return apiService.getTempletChartsData(id);
	}

	/**
	 * 获取图表数据
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/getChartsData")
	public Result<?> getChartsData(@RequestParam(name = "id", required = true) String id, @RequestParam("params") String paramString) {
		OnlGraphreportHead head = headService.getById(id);
		if (head == null) {
			return Result.error("实体不存在");
		} else {
			return Result.ok(apiService.queryChartDataSource(head, paramString));
		}
	}

	/**
	 * 根据code获取图表数据
	 * 
	 * @param code
	 * @return
	 */
	@GetMapping(value = "/getChartsDataByCode")
	public Result<?> getChartsDataByCode(@RequestParam(name = "code", required = true) String code, @RequestParam("params") String paramString) {
		OnlGraphreportHead head = headService.queryByCode(code);
		if (head == null) {
			return Result.error("实体不存在");
		} else {
			return Result.ok(apiService.queryChartDataSource(head, paramString));
		}
	}

	/**
	 * 导出excel
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/exportXls")
	public void exportXls(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取参数
		String name = request.getParameter("name");
		String dataSourceString = URLDecoder.decode(request.getParameter("dataSource"), "UTF-8");
		String entitysString = URLDecoder.decode(request.getParameter("entitys"), "UTF-8");

		// 非空判断
		if (StringUtils.isEmpty(dataSourceString) || StringUtils.isEmpty(entitysString)) {
			throw new Exception("缺少必要的参数（dataSource、entitys）");
		}
		if (StringUtils.isEmpty(name)) {
			name = "ExportExecel";
		}
		// 转为JSONArray
		JSONArray entitysJson = JSONObject.parseArray(entitysString);
		JSONArray dataSourceJson = JSONObject.parseArray(dataSourceString);

		// 装载 entity
		List<ExcelExportEntity> entityList = new ArrayList<ExcelExportEntity>();
		for (int i = 0; i < entitysJson.size(); i++) {
			JSONObject entity = entitysJson.getJSONObject(i);
			String key = entity.getString("key");
			String alias = entity.getString("alias");
			// 默认宽度30
			entityList.add(new ExcelExportEntity(alias, key, 30));
		}

		// 装载 list
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (int i = 0; i < dataSourceJson.size(); i++) {
			JSONObject data = dataSourceJson.getJSONObject(i);
			// 遍历 keys
			Iterator<String> iterator = data.keySet().iterator();
			Map<String, String> map = new HashMap<String, String>();
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				String value = data.getString(key);
				map.put(key, value);
			}
			list.add(map);
		}

		ServletOutputStream out = null;
		try {

			// 导出Execl
			Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(name, name), entityList, list);

			// step.4 根据浏览器进行转码，使其支持中文文件名
			String browse = BrowserUtils.checkBrowse(request);
			if ("MSIE".equalsIgnoreCase(browse.substring(0, 4))) {
				response.setHeader("content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(name, "UTF-8") + ".xls");
			} else {
				String newtitle = new String(name.getBytes("UTF-8"), "ISO8859-1");
				response.setHeader("content-disposition", "attachment;filename=" + newtitle + ".xls");
			}

			// 写出到view
			out = response.getOutputStream();
			workbook.write(out);
		} catch (Exception e) {
		} finally {
			try {
				out.flush();
				out.close();
			} catch (Exception e) {
			}
		}

	}

}
